package com.lockapp.database;

import com.lockapp.R;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class LockAppDatabase extends SQLiteOpenHelper {

	private static final String DATABASE_NAME = "lock.dbbaa12";
	private static final int DATABASE_VERSION = 1;
	private Context context;
	
	public LockAppDatabase(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		this.context = context;
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		String[] sql = context.getString(R.string.sql_create).split("\\|");
		for(String s : sql){
			Log.i("SQL", s);
		}
		db.beginTransaction();
		try {
			execMultipleSQL(db, sql);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("ERRO AO CRIAR TABELAS", e.getMessage());
		} finally {
			db.endTransaction();
		}
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		String[] sql = context.getString(R.string.sql_upgrade).split("\\|");
		for(String s : sql){
			Log.i("SQL", s);
		}
		db.beginTransaction();
		try {
			execMultipleSQL(db, sql);
			db.setTransactionSuccessful();
		} catch (Exception e) {
			Log.e("ERRO AO ATUALIZAR TABELAS", e.getMessage());
		} finally {
			db.endTransaction();
		}
	}
	
	 private void execMultipleSQL(SQLiteDatabase db, String[] sql) {
        for (String s : sql) {
            if (s.trim().length() > 0) {
                    db.execSQL(s);
            }
        }
    }

}
